#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>

#define MAX_TEXT 2048

struct shared_struct
{
	int    written;          //作为一个标志，非0：表示可读，0表示可写
	char   text[MAX_TEXT];   //记录写入和读取的文本
};

int main()
{
	int                   starting = 1;
	void                  *shm = NULL;       //共享内存的原始地址
	struct shared_struct  *shared = NULL;
	char                  buffer[BUFSIZ + 1];//用于保存输入的文本
	int                   shmid;             //共享内存标识符

	//创建共享内存
	shmid = shmget((key_t)1234, sizeof(struct shared_struct), 0666|IPC_CREAT);
	if(shmid == -1)
	{
		printf ("shmget creat failed\n");
		return -1;
	}

	//将共享内存连接到当前进程的地址空间
	shm = shmat(shmid, (void*)0, 0);
	if(shm == (void*)-1)
	{
		printf("shmat failed\n");
		return -2;
	}

	//设置共享内存
	shared = (struct shared_struct*)shm;


	while(starting) //向共享内存中写数据
	{
		//等待数据被读取,不能向共享内存中写入文本
		while(shared->written == 1)
		{
			sleep(1);
			printf("Waiting...\n");
		}
		
                //向共享内存中写入数据
		printf("请输入信息: ");
		fgets(buffer, BUFSIZ, stdin);
		strncpy(shared->text, buffer, MAX_TEXT);

		//写完数据，设置written使共享内存段可读
		shared->written = 1;

		//输入了end，退出循环（程序）
		if(strncmp(buffer, "end", 3) == 0)
			starting = 0;
	}
	//把共享内存从当前进程中分离
	if(shmdt(shm) == -1)
	{
		printf( "shmdt failed\n");
		return -3;
	}
	sleep(2);
	return 0;
}
